#include "iTubePanel.h"


BEGIN_EVENT_TABLE(iTubePanel, MainPanel)
	EVT_BUTTON( ID_SEARCH_BUTTON, iTubePanel::OnSearch )
	EVT_TEXT_ENTER( ID_MAIN_TEXT, iTubePanel::OnSearch )
	EVT_LISTBOX( ID_LIST_BOX,iTubePanel::OnListSelect )
	EVT_BUTTON( ID_CLEAR_BUTTON, iTubePanel::OnClear )
	EVT_BUTTON( ID_DOWNLOAD_BUTTON, iTubePanel::OnDownload )
	EVT_DOWNLOAD(iTubePanel::OnDownloadEvent)
END_EVENT_TABLE()

iTubePanel::iTubePanel( wxWindow* parent )
	: MainPanel( parent )
{

DownloadInProgress = false; //initialize the program	
	
}



iTubePanel::~iTubePanel()
{


}


//create a search query and download the search results feed from the api, which we can parse
//later for all of the resulting videos' urls and thumbnails
void iTubePanel::OnSearch( wxCommandEvent& event )
	{
	
	wxString SearchText = MainSearchBox->GetValue();
	VidDescriptionBox->SetLabel(wxT("")); //make sure the description box is empty
	SearchResults->Set(0,(const wxString*)wxT(""),NULL);//clear the list box

	
	
	Searcher* VideoSearch = new Searcher(SearchText);
	wxString SearchResultsFileName = VideoSearch->SearchForVideos();
	
		
		Videos = VideoSearch->GetAllVideoInformation();
		//Videos = VideoSearch->AddAuthorsToTitles();  //we're not going to have authors in the list box
		
		//put results in the list box
		SearchResults->InsertItems(Videos.Title,0);

	delete VideoSearch;

	
}	//void iTubePanel::OnSearch( wxCommandEvent& event )

//when user selects list box, change the description accordingly

void iTubePanel::OnListSelect( wxCommandEvent& event )
	{
	
	 SelectionIndex = SearchResults->GetSelection();
	
	wxString description;
	wxString author;
	
	description = Videos.Description.Item(SelectionIndex);
	author = Videos.Author.Item(SelectionIndex);
	

	

	//make sure the description's not too big
	if(description.Len() > 393)  //313 is a decent number too
		{
	wxString trunc_label;
	description.Truncate(static_cast<size_t>(393));
	description.Append(wxT("...(continued)"));
		}
	//tack on the author's username at the end of the description
	description.Append(wxT("\n\n\n"));
	description.Append(wxT("Uploaded By: "));
	description.Append(author);
	VidDescriptionBox->SetLabel(description);
	
	//some magic to make the contents redraw...
	//not sure why Update doesn't work
	wxSize size = this->GetSize();
	this->SetSize(size.x+1,size.y);
	this->SetSize(size.x,size.y);

	//now for displaying the thumbnail...
	
	wxURL url( Videos.ThumbnailUrl.Item(SelectionIndex) );
	if(url.GetError() != wxURL_NOERR)
		{
		wxMessageBox(wxT("Could not access thumbnail from: ")+ Videos.ThumbnailUrl.Item(SelectionIndex));
		}
	else{
		wxInputStream *vidThumbStream = NULL;
		vidThumbStream = url.GetInputStream();
		wxImage *Thumbnail = new wxImage(*vidThumbStream,wxBITMAP_TYPE_JPEG);
		
		delete Thumbnail;
		delete vidThumbStream;
	//now Thumbnail contains our image


		}
	
	

		
	
	}

void iTubePanel::OnClear( wxCommandEvent& event )
	{
		MainSearchBox->Clear();
		SearchResults->Clear();
		VidDescriptionBox->SetLabel(wxT(""));
		SelectionIndex = NULL;
	}

void iTubePanel::OnDownload( wxCommandEvent& event )
	{

		//get the direct link to the video for later downloading
	DownloadInProgress = true;
	CompletedFilename = wxT("");

	wxString Link, LinkName;
	LinkGrabber* VideoLink = new LinkGrabber(Videos.Url.Item(SelectionIndex));
	
	Link = VideoLink->GetDirectLink();
	LinkName = VideoLink->GetFnameId();

	#ifdef MYDEBUG
	wxMessageBox( wxT("First Direct link to download video: ") + Link + wxT(" and Video_Id: " + LinkName ) );
#endif
	delete VideoLink;

	DownloadMgrDlg* w_DldMgrDlg = new DownloadMgrDlg(this);
	w_DldMgrDlg->Show(true);
	w_DownDialog = w_DldMgrDlg;

	w_DldMgr = new DownloadMgr(Link, LinkName, this);
	wxASSERT_MSG(w_DldMgr->CheckQueueAndIdCount() == true,wxT("Queue and Id counts don't match in iTubePanel::OnDownload()") );

	wxString CompletedFilename;
	if(w_DldMgr->ExistsInQueue(0) == true)
		{
		CompletedFilename = w_DldMgr->Download(0);
		

		#ifdef MYDEBUG
		wxMessageBox(wxT("Called w_DldMgr->Download(0)"));
#endif
		}
	else
		{
		wxMessageBox(wxT("Index wasn't in queue in iTubePanel::OnDownload()"));
		DownloadInProgress = false;
		}
	
	//if(w_DldMgr->VerifyCompletedFile(CompletedFilename) == false)
	//	{
	//	wxMessageBox(wxT("File could not be verified"));
	//	}
	//else
	//	{
		
	//	}

	}
	

void iTubePanel::OnDownloadEvent(libvdnEvent& event)
	{
	
	
	if(event.GetDownloadStatus() == libvdnEvent::DOWNLOAD_FAIL)
		{
		int err = event.GetErrorCode();
		wxString s_err = wxString::Format(wxT("%d"),err);
		DownloadInProgress = false;
		
		//DEBUG
#ifdef MYDEBUG
		wxMessageBox(wxT("Download has stopped or finished with code: ")+ s_err);
		//*****
#endif
		}

	if(event.GetDownloadStatus() == libvdnEvent::DOWNLOAD_INPROGRESS)
		{
		w_DownDialog->GetEventHandler()->AddPendingEvent(event);
		}

	if(event.GetDownloadStatus() == libvdnEvent::DOWNLOAD_COMPLETE)
		{
		//DEBUG
		if(DownloadInProgress == true){
		DownloadInProgress = false;  //for whatever reason, this *must* be set false before doing anything else
									//otherwise it repeats ~3 times. no idea why, maybe a bug in wxwidgets or
									//something i'm doing with the threading
			wxMessageBox(wxT("Download has completed"));
		

		w_DownDialog->Close(); //close the download manager dialog
		
		/*  commented out for release build.  For some reason the dialog isn't showing,
		//so I'll wait for the next release to get it fixed.
		RenameDlg* RenameBox = new RenameDlg(this,CompletedFilename);
		RenameBox->Show(false);
		
		if(RenameBox->Show(true) != true){
			wxMessageBox(wxT("Either couldn't show rename dialog or it is already showing"));
			}
		RenameBox->Raise();
		*/
		
			}

		}



	}










